package com.liuhm.controller;

import com.liuhm.exception.BDException;
import com.liuhm.utils.FileToPdfUtils;
import com.liuhm.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 上传文件类
 *
 * @author liuhaomin
 * @date 2020/6/30
 */
@Controller
@Api(description = "上传文档")
public class UploadController {

    @Value("${demo.upload}")
    private String uploadPath;

    @GetMapping("/")
    @ApiOperation("文件上传页面")
    public String index() {
        return "index";
    }


    @PostMapping("/upload")
    @ApiOperation("文件上传类")
    @ResponseBody
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            throw new BDException("上传失败，请选择文件");
        }
        String originalFilename = file.getOriginalFilename().indexOf("\\") > 0 ? file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\") + 1) : file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename;
        File f = new File(uploadPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        File dest = new File(uploadPath + "/" + fileName);
        try {
            file.transferTo(dest);
            String pdfPath = FileToPdfUtils.officeToPdf(uploadPath + "/" + fileName, uploadPath + "/" + "pdf");
            Map<String, Object> map = new HashMap<>();
            map.put("path", (uploadPath + "/" + fileName).replace(uploadPath, ""));
            map.put("pdfPath", pdfPath != null ? pdfPath.replace(uploadPath, "") : "");
            return R.ok(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("上传失败！");
    }
}
